import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams} from 'ionic-angular';
import {SideMenuService} from "../../../services/common/side-menu.service";
import {TabsPage} from "../../tabs/tabs";
import {WebcastFavoriteListProvider} from "../../../providers/webcast/webcast-favorite-list/webcast-favorite-list";
import * as moment from 'moment';
import {MessageBushService} from "../../../services/common/message-bush.service";
import {LoadingService} from "../../../services/common/loading.service";

/**
 * Generated class for the WebcastFavoriteListPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-webcast-favorite-list',
  templateUrl: 'webcast-favorite-list.html',
    providers: [SideMenuService, WebcastFavoriteListProvider]
})
export class WebcastFavoriteListPage {

    openRoot = (name, index) => this.openTab(name, index);

    openMenu(myEvent) {
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index) {
        this.navCtrl.popToRoot()
        this.tabsPage.openPage({name: name, index: index});
    }

    moment = moment;
    isScrolling = false;
    isArriveBottom = false;
    nowStamp: number = new Date().getTime();
    resultStamp: number;
    @ViewChild(Content) content: Content;

    castFavList: any;
    castFavNum: number = 0;
    isLoaded: boolean = false;

    //现在时间
    todayDate: Date = new Date();

  constructor(public navCtrl: NavController,
              private sideMenuService: SideMenuService,
              public changeRef: ChangeDetectorRef,
              public webcastFavoriteListProvider: WebcastFavoriteListProvider,
              public tabsPage: TabsPage,
              private loadingService: LoadingService,
              public navParams: NavParams) {
  }

  ionViewDidLoad() {
      let status = MessageBushService.getMessage(MessageBushService.keys.webCastFavoriteUpdated);
      if (status == '0' || status == null) {
          this.getCastFavoriteList();
      }
  }

  ionViewDidEnter() {
      let status = MessageBushService.getMessage(MessageBushService.keys.webCastFavoriteUpdated);
      if (status === '1') {
          this.getCastFavoriteList();
          this.loadingService.dismissLoading();
      }
      MessageBushService.setMessage(MessageBushService.keys.webCastFavoriteUpdated, '0');
  }

  //获取直播收藏列表
    getCastFavoriteList() {
      this.loadingService.showLoading();
        this.webcastFavoriteListProvider.getCastFavoriteList().subscribe(res => {

            this.castFavList = res;
            if (this.castFavList) {
                this.castFavNum = this.castFavList.length;

                //处理状态
                for(var i =0;i<this.castFavList.length;i++) {
                    this.castFavList[i]['castText'] = this.formatCastDate(this.castFavList[i]['castStatus'],this.castFavList[i]['castDate']);
                }
            }

            this.isLoaded = true;
            this.loadingService.dismissLoading();
        }, error2 => {
            this.loadingService.dismissLoading();
        });
    }

    //跳转到直播详情
    goCastDetail(castId: string, castTitle: string, roomId: string) {

      this.navCtrl.push('WebcastDetailPage',
          {"castId": castId, "castTitle": castTitle, "roomId": roomId});
    }

    formatCastTitle(title: string) {
      if (title.length>25) {
          return title.substring(0, 25) + '...';
      }

      return title;
    }

    // formatCastDate(castDate: number) {
    //   let date = moment(castDate*1000).format('YYYY/MM/DD HH:MM');
    //   let now  = moment(this.nowStamp).format('YYYY/MM/DD HH:MM');
    //   // console.log(date);
    //   // console.log(now);
    //   let result = '';
    //
    //   this.resultStamp = Math.floor((this.nowStamp - castDate*1000)/(3600*24*1000));
    //
    //   // console.log(this.resultStamp);
    //   if (date.split(' ')[0] == now.split(' ')[0]) {
    //       result = '今天'+date.split(' ')[1];
    //   } else {
    //       if (this.resultStamp == -1) {
    //           result = '明天' + date.split(' ')[1];
    //       } else if (this.resultStamp < -1) {
    //           result = (-this.resultStamp) + '天后';
    //       } else {
    //           result = date.split(' ')[0];
    //       }
    //   }
    //
    //   return result;
    // }

    formatCastDate(castStatus:number,castDate:number) {
        //直播日期
        let liveDate = moment(castDate*1000).format('YYYY/MM/DD');
        //今天
        let nowDate = moment(this.todayDate.getTime()).format('YYYY/MM/DD');
        //明天
        let nextDate = moment(this.todayDate.getTime()).add(1, 'days').format('YYYY/MM/DD');

      if (castStatus == 5) {
          return liveDate;
      } else if (castStatus == 1) {
          return '正在直播';
      } else if (castStatus == 2) {
          if (liveDate == nowDate) {
              return '今天'+moment(castDate*1000).format('YYYY/MM/DD HH:mm').split(' ')[1];
          } else if (liveDate == nextDate) {
              return '明天'+moment(castDate*1000).format('YYYY/MM/DD HH:mm').split(' ')[1];
          } else {
              return liveDate;
          }
      }
    }

    goBack(){
        this.navCtrl.pop();
        // this.openTab('HomePage', 4);
    }

    pullDownRefresh(refresher) {
        this.webcastFavoriteListProvider.getCastFavoriteList().subscribe(res => {
            this.castFavList = res;
            if (this.castFavList) {
                this.castFavNum = this.castFavList.length;

                //处理状态
                for(var i =0;i<this.castFavList.length;i++) {
                    this.castFavList[i]['castText'] = this.formatCastDate(this.castFavList[i]['castStatus'],this.castFavList[i]['castDate']);
                }
            }
            refresher.complete();
        }, error2 => {
            refresher.complete();
        });
    }

    scrollStart(e) {
        this.isScrolling = true;
    }

    scrollEnd(e) {
        this.isScrolling = false;
    }

    scrolling() {
        const dimensions = this.content.getContentDimensions();
        const temp1 = dimensions.scrollHeight - dimensions.scrollTop - dimensions.contentHeight < 100;

        if (temp1 !== this.isArriveBottom) {
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }
    }

    goUp() {
        if (this.isScrolling) {
            setTimeout(() => {
                this.goUp();
            }, 300);
            return;
        }
        this.content.scrollToTop();
    }

}
